package com.atguigu.exer;

import java.util.concurrent.locks.ReentrantLock;

//解决线程安全问题的方式三:Lock锁---JDK5.0新增
class Windows5 implements Runnable{
    //1.实例化ReentrantLock
    private ReentrantLock lock=new ReentrantLock(); //Lock是接口，ReentrantLock是其子类
    private int ticket=100;

    public static void main(String[] args) {
        Windows5 windows=new Windows5();
        Thread t1=new Thread(windows);
        Thread t2=new Thread(windows);
        Thread t3=new Thread(windows);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

    public void run(){
        while(true){
            try {
                //2.调用lock方法
                lock.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "在售票，票号为:" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }finally {
                //3.调用解锁的方法
                lock.unlock();
            }
        }
    }
}
public class LockTest {

}
